<template>
    <!-- 基本信息 -->
    <div>
      <div class="title-wrapper">
        <title-name title="风险上报信息"></title-name>
        <a-icon
          v-if="showPlanBoardVisible"
          :type="planBoardVisible ? 'up' : 'down'"
          @click="planBoardVisible = !planBoardVisible"
        />
      </div>
      <div v-if="planBoardVisible">
        <!-- 表单信息 -->
        <custom-form ref="ruleForm" isValidate :formList="formList" :form="form" :editModel="onlyRead ? 'V' : 'E'"
          :isEmit="false">
            <!-- 风险损失 -->
            <template slot="riskTable" slot-scope="scoped">
              <!-- 新增按钮 -->
              <a-button size="default" type="primary" @click="visible = true" v-if="!onlyRead" style="margin-bottom: 20px;"> 选择 </a-button>
              <a-table
                :pagination="false"
                size="default"
                :rowKey="(record, index) => record ? (record.id + index) : index"
                bordered
                :columns="onlyRead ? columns2 : columns1"
                :data-source="dataSource"
              >
                <!-- 补充描述 -->
                <template slot="supplementDescription" slot-scope="text, record, index">
                  <EditableCell type="textarea" :auto-size="{ minRows: 1, maxRows: 4 }" :maxLength="300" :key="index + '-supplementDescription'" :text="text" @change="onCellChange(record, 'supplementDescription', $event)" :disabled="record.operation === false"></EditableCell>
                </template>
                <!-- 操作 -->
                <template
                  slot="action"
                  slot-scope="text, record, index"
                >
                  <a-popconfirm title="请确认是否要删除？" @confirm="() => onDelete(record)">
                    <a class="base-btn del_btn">删除</a>
                  </a-popconfirm>
                </template>
              </a-table>
            </template>
        </custom-form>
      </div>
      
      <a-modal
        centered
        title="风险损失"
        :visible="visible"
        ok-text="选中提交"
        width="1200px"
        @cancel="visible = false"
        @ok="handleConfirm"
      >
        <RiskJudgmentCriteria :isModal="true" ref="RiskJudgmentCriteria" :outSelectedRowKeys="outSelectedRowKeys"></RiskJudgmentCriteria>
      </a-modal>
    </div>
  </template>
  
  <script>
  import EditableCell from '@/views/quality/riskIdentification/components/EditableCell'
  import RiskJudgmentCriteria from '@/views/quality/riskJudgmentCriteria' // 项目
  import SelectProjectType from '@/components/Select/SelectProjectType' // 工程类别
  import SelectTreeSubItem from '@/components/Select/SelectTreeSubItem' // 分部分项
  const columns1 = [
    {
      title: '损失类型',
      dataIndex: 'treeName',
      width: 180,
    },
    {
      title: '损失描述',
      dataIndex: 'description',
      ellipsis: true,
    },
    {
      title: '补充描述',
      dataIndex: 'supplementDescription',
      scopedSlots: { customRender: 'supplementDescription' },
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: 100,
      scopedSlots: { customRender: 'action' },
    }
  ]
  const columns2 = [
    {
      title: '损失类型',
      dataIndex: 'treeName',
      width: 180,
    },
    {
      title: '损失描述',
      dataIndex: 'description',
      ellipsis: true,
    },
    {
      title: '补充描述',
      dataIndex: 'supplementDescription',
    },
  ]
  export default {
    name: 'a' + Date.now(),
    components: {
      RiskJudgmentCriteria,
      EditableCell
    },
    props: {
      // 表单
      form: {
        type: Object,
        default: () => ({})
      },
      // 只读模式
      onlyRead: {
        type: Boolean,
        default: () => false
      },
      // 是否显示箭头
      showPlanBoardVisible: {
        type: Boolean,
        default: () => false
      },
      // 默认展开
      defaultPlanBoardVisible: {
        type: Boolean,
        default: () => true
      }
    },
    watch: {
        defaultPlanBoardVisible: {
          handler(val) {
            this.planBoardVisible = val
          },
          immediate: true,
          deep: true
        },
        'form.projectId': {
          handler(newVal, oldVal) {
            if (newVal !== oldVal && oldVal) {
              this.$emit('updateForm', {projectTypeId: '', subProjectId: ''})
            }
          },
          immediate: true,
          deep: true
        },
        'form.lossInfos': {
          handler(newVal) {
            if (newVal) {
              this.dataSource = newVal.map(item => {
                if (item.type) {
                  item.level = item.type.level
                  item.id = item.type.id
                  item.description = item.type.description
                  item.treeName = item.type.treeName
                }
                return item
              })
              this.handleData()
            }
          },
          immediate: true,
          deep: true
        },
    },
    data() {
      return {
        planBoardVisible: false,
        visible: false,
        dataSource: [],
        outSelectedRowKeys: [],
        columns1,
        columns2,
      }
    },
    created() {
    },
    computed: {
      // 表单配置项
      formList() {
        let list = [
            {
              type: SelectProjectType,
              keyName: this.onlyRead ? 'projectTypeName' : 'projectTypeId',
              label: '工程类别',
              disabled: this.onlyRead,
              attrs: {
                id: this.form.projectId || '',
                init: false
              },
              change: (e) => {
                if (e) {
                  this.$emit('updateForm', {subProjectId: ''})
                }
              }
            },
            {
                type: SelectTreeSubItem,
                disabled: this.onlyRead,
                keyName: this.onlyRead ? 'subProjectName' : 'subProjectId',
                label: '分部分项',
                attrs: {
                    projectId: (this.form.projectId && this.form.projectTypeId) ? this.form.projectId : '',
                    typeId: (this.form.projectId && this.form.projectTypeId) ? this.form.projectTypeId : '',
                    init: false,
                }
            },
            {
              keyName: 'projectPosition',
              type: 'a-input',
              label: '工程部位',
              rule: {
                required: true,
                whitespace: true,
                message: '请输入工程部位',
                trigger: 'change'
              },
            },
            {
              keyName: 'name',
              type: 'a-input',
              label: '风险名称',
              rule: {
                required: true,
                whitespace: true,
                message: '请输入风险名称',
                trigger: 'change'
              },
            },
            {
              type: 'BaseTextarea',
              keyName: 'riskDescription',
              label: '风险描述',
              attrs: {
                maxLength: 1000
              },
              rule: {
                required: true,
                whitespace: true,
                message: '请输入风险描述',
                trigger: 'change'
              },
              span: 24
            },
            {
              slot: true,
              keyName: 'riskTable',
              label: '风险损失',
              disabled: true,
              span: 24
            },
            {
              type: 'a-input',
              keyName: 'levelName',
              label: '上报风险等级',
              disabled: true,
            },
            {
              type: 'BaseTextarea',
              keyName: 'handleOpinion',
              label: '处理意见',
              attrs: {
                maxLength: 1000
              },
              rule: {
                required: true,
                whitespace: true,
                message: '请输入处理意见',
                trigger: 'change'
              },
              span: 24
            },
        ]
  
        return list
      },
    },
    methods: {
      handleConfirm() {
        if (this.$refs.RiskJudgmentCriteria.selectRow) {
          const selectRow = this.$refs.RiskJudgmentCriteria.selectRow
          const arr = this.dataSource.concat(selectRow)
          const obj = {}
          this.dataSource = arr.reduce((total, currentValue) => {
            obj[currentValue.id] ? '' : (obj[currentValue.id] = true && total.push(currentValue))
            return total
          }, [])
          this.dataSource = this.dataSource.map(item => {
            if (!item.hasOwnProperty('supplementDescription')) {
              item.supplementDescription = ''
            }
            return item
          })
          this.outSelectedRowKeys = selectRow.map(item => item.id)
          this.handleData()
          this.visible = false
        }
      },
      handleData() {
        const levelCode = []
        const levelName = ['一般风险', '较大风险', '重大风险', '特大风险']
        this.dataSource.forEach(item => {
          if (item.level && item.level.code) {
            if (!levelCode.includes(item.level.code)) {
              levelCode.push(+item.level.code)
            }
          }
        });
        this.form.levelName = levelName[Math.max(...levelCode)]
      },
      onDelete(item) {
        const dataSource = [...this.dataSource]
        this.dataSource = dataSource.filter((el) => el.id !== item.id)
        this.outSelectedRowKeys = this.dataSource.map(item => item.id)
        this.handleData()
      },
      onCellChange(item, dataIndex, value) {
        const dataSource = [...this.dataSource]
        const target = dataSource.find((el) => el.id === item.id)
        if (target) {
          target[dataIndex] = value
          this.dataSource = dataSource
        }
      },
    },
  }
  </script>

<style lang="less" scoped>
.title-wrapper {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  .titleName {
    margin: 0;
  }
  .anticon {
    margin-left: 5px;
    font-size: 18px;
  }
}
</style>